package cn.exrick.xboot.modules.downloadResources.controller;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

/**
 * 多线程下载
 *
 * @author jam
 *
 */
@Slf4j
public class ThreadDownloader {

    public static void main(String[] args) {
        HttpGet httpGet = null;
        String localFileName = null;
        String fileOriName = null;
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 这里我设置了超时时间的配置，也可以不设
            RequestConfig timeoutConfig = RequestConfig.custom()
                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                    .setSocketTimeout(5000).build();
            // download_url为下载文件接口地址
            // 文件下载接口是直接返回的文件流
            httpGet = new HttpGet("http://47.92.27.141:8899/xboot/downloadResources/downloadFile?fileName=app-release.apk");
            httpGet.setConfig(timeoutConfig);
            HttpResponse downLoadResponse = httpClient.execute(httpGet);
            StatusLine statusLine = downLoadResponse.getStatusLine();
            // 响应码
            int statusCode = statusLine.getStatusCode();
            // 请求成功
            if (statusCode == 200) {
                // 获取接口返回的文件流
                HttpEntity entity = downLoadResponse.getEntity();
                InputStream input = entity.getContent();
                // 储存到本地文件系统，fileRealName为你想存的文件名称
                OutputStream output = new FileOutputStream(new File("C://testFile/app-release.apk"));
                int len = 0;
                byte[] ch = new byte[1024];
                while ((len = input.read(ch)) != -1) {
                    output.write(ch, 0, len);
                }
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }

    }


}